import React from 'react';
import { postAccount } from '@/services/aqchain-antd/account';
import { message } from 'antd';
import { ModalForm, ProFormText } from '@ant-design/pro-form';
import { useModel } from '@@/plugin-model/useModel';

const RegisterModalForm: React.FC<{
  modalVisit: boolean;
  setModalVisit: React.Dispatch<React.SetStateAction<boolean>>;
}> = (props) => {
  const { modalVisit, setModalVisit } = props;
  const { initialState, setInitialState } = useModel('@@initialState');
  const { provider } = initialState!;

  return (
    <ModalForm<API.ModelsAccountPost>
      title="注册钱包信息"
      width={500}
      onFinish={async (values) => {
        try {
          if (provider === undefined) {
            // todo 处理未安装钱包流程
            console.error('钱包初始化失败');
            return;
          }
          const signer = provider.getSigner();
          values.address = await signer.getAddress();
          values.signature = await signer.signMessage(
            'Account Operation Sign Message',
          );
          const response = await postAccount({}, values);
          const currentAccount = response.data;
          setModalVisit(false);
          // setInitialState({ ...initialState, currentAccount });
          window.location.reload();
        } catch (error) {
          message.error(error);
        }
      }}
      visible={modalVisit}
      onVisibleChange={setModalVisit}
    >
      <ProFormText
        name="username"
        label="用户名"
        placeholder="请输入用户名"
        rules={[
          {
            required: true,
            message: '请输入用户名',
          },
        ]}
      />
      <ProFormText
        name="mail"
        label="邮箱地址"
        placeholder="请输入邮箱地址"
        rules={[
          {
            required: true,
            message: '请输入邮箱地址',
          },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
          },
        ]}
      />
    </ModalForm>
  );
};

export default RegisterModalForm;
